import api from './index';

export interface KnowledgeItem {
  id: string;
  title: string;
  description?: string;
  content?: string;
  fileId?: string;
  fileType?: string;
  fileUrl?: string;
  categoryId?: string;
  tags?: string[];
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  viewCount?: number;
  isPublic: boolean;
}

export interface KnowledgeListParams {
  page?: number;
  size?: number;
  categoryId?: string;
  tag?: string;
  keyword?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

export interface KnowledgeListResponse {
  items: KnowledgeItem[];
  total: number;
  page: number;
  size: number;
}

// 获取知识列表
export const getKnowledgeList = (params: KnowledgeListParams) => {
  return api.get<any, KnowledgeListResponse>('/knowledge', { params });
};

// 获取知识详情
export const getKnowledgeDetail = (id: string) => {
  return api.get<any, KnowledgeItem>(`/knowledge/${id}`);
};

// 创建知识
export const createKnowledge = (data: Partial<KnowledgeItem>) => {
  return api.post<any, KnowledgeItem>('/knowledge', data);
};

// 更新知识
export const updateKnowledge = (id: string, data: Partial<KnowledgeItem>) => {
  return api.put<any, KnowledgeItem>(`/knowledge/${id}`, data);
};

// 删除知识
export const deleteKnowledge = (id: string) => {
  return api.delete<any, void>(`/knowledge/${id}`);
};

// 上传文件
export const uploadFile = (file: File, onProgress?: (percent: number) => void) => {
  const formData = new FormData();
  formData.append('file', file);
  
  return api.post<any, { fileId: string, fileUrl: string }>('/files/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total && onProgress) {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(percent);
      }
    },
  });
};